<script setup>
import { getNewsList, createNews, updateNews, deleteNews } from '@/api/backend/content';
import { uploadPicture } from '@/api/backend/upload';
import { FilterMatchMode } from '@primevue/core/api';
import { useToast } from 'primevue/usetoast';
import { onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useConfirm } from 'primevue/useconfirm';

const route = useRoute();
const toast = useToast();
const confirm = useConfirm();

// 状态管理
const dt = ref();
const products = ref([]);
const isLoading = ref(false);
const productDialog = ref(false);
const deleteProductsDialog = ref(false);
const product = ref(initProductState());
const selectedProducts = ref([]);
const filters = ref({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS }
});

// 初始化产品状态
function initProductState() {
    return {
        id: null,
        title: '',
        content: '',
        pic: '',
        cate_id: route.query.classid,
        cate_name: '',
        ispic: false,
        istop: false,
        isnice: false,
        islock: false
    };
}

// 加载数据（带防抖和请求取消）
let abortController = null;
const loadContent = async () => {
    try {
        abortController?.abort();
        abortController = new AbortController();

        isLoading.value = true;
        const { code, data } = await getNewsList(
            { cate_id: route.query.classid },
            {
                signal: abortController.signal
            }
        );

        if (code === 200) {
            products.value = data.map((item) => ({
                ...item,
                ispic: Boolean(item.ispic), // 确保布尔类型
                istop: Boolean(item.istop),
                isnice: Boolean(item.isnice),
                islock: Boolean(item.islock)
            }));
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            showError('加载失败', error.message);
        }
    } finally {
        isLoading.value = false;
        abortController = null;
    }
};

const isSaving = ref(false);
// 操作处理
const handleSave = async () => {
    isSaving.value = true;
    try {
        const payload = {
            ...product.value,
            cate_id: route.query.classid // 确保分类ID传递
        };

        const apiMethod = product.value.id ? updateNews : createNews;
        const { code } = await apiMethod(payload);

        if (code === 200) {
            await loadContent();
            showSuccess('操作成功', product.value.id ? '更新成功' : '创建成功');
            closeDialog();
        }
    } catch (error) {
        showError('操作失败', error.message);
    } finally {
        isSaving.value = false;
    }
};

const handleDelete = async (id) => {
    try {
        const { code } = await deleteNews(id);
        if (code === 200) {
            await loadContent();
            showSuccess('删除成功');
        }
    } catch (error) {
        showError('删除失败', error.message);
    }
};

const handleBatchDelete = async () => {
    try {
        const deletePromises = selectedProducts.value.map((item) => deleteNews(item.id));
        await Promise.all(deletePromises);
        await loadContent();
        showSuccess('批量删除成功');
        deleteProductsDialog.value = false;
        selectedProducts.value = [];
    } catch (error) {
        showError('删除失败', error.message);
    }
};
// 新增切换处理函数
const handleToggleChange = async (field, item) => {
    try {
        const payload = { ...item, [field]: item[field] };
        const { code } = await updateNews(payload);
        if (code === 200) {
            showSuccess('状态更新成功');
            await loadContent();
        }
    } catch (error) {
        showError('更新失败', error.message);
        // 回滚状态
        item[field] = !item[field];
    }
};
// 确认对话框
const confirmDelete = (item) => {
    confirm.require({
        message: `确定要删除 ${item.name} 吗？`,
        header: '删除确认',
        accept: () => handleDelete(item.id)
    });
};

// 工具函数
const showSuccess = (summary, detail = '') => {
    toast.add({ severity: 'success', summary, detail, life: 3000 });
};

const showError = (summary, detail = '') => {
    toast.add({ severity: 'error', summary, detail, life: 3000 });
};

const closeDialog = () => {
    productDialog.value = false;
    product.value = initProductState();
};

function openNew() {
    product.value = {};
    productDialog.value = true;
}

const uploadImage = async () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    input.onchange = async (e) => {
        const file = e.target.files[0];
        const formData = new FormData();
        formData.append('image', file);

        try {
            const { code, data } = await uploadPicture(formData);
            if (code === 200) {
                product.value.pic = data.url;
                showSuccess('图片上传成功');
            }
        } catch (error) {
            showError('上传失败', error.message);
        }
    };
    input.click();
};

// 生命周期和监听
onMounted(loadContent);
onUnmounted(() => {
    abortController?.abort();
});
watch(() => route.query.classid, loadContent);
</script>

<template>
    <div class="content-manager">
        <Breadcrumb :home="{ icon: 'pi pi-home', to: '/' }" :model="[{ label: '网站管理' }, { label: '网站设置' }]" />

        <div class="card">
            <Toolbar class="mb-4">
                <template #start>
                    <Button label="新增" icon="pi pi-plus" severity="secondary" @click="openNew" />
                    <Button label="删除选中" icon="pi pi-trash" severity="secondary" :disabled="!selectedProducts.length" @click="deleteProductsDialog = true" />
                </template>

                <template #end>
                    <IconField iconPosition="left">
                        <InputIcon class="pi pi-search" />
                        <InputText v-model="filters.global.value" placeholder="搜索..." />
                    </IconField>
                </template>
            </Toolbar>

            <DataTable ref="dt" v-model:selection="selectedProducts" :value="products" :loading="isLoading" paginator :rows="10" removableSort dataKey="id" filterDisplay="menu" :filters="filters">
                <Column selectionMode="multiple" headerStyle="width: 3rem" />
                <Column field="title" header="标题" />
                <Column field="cate_name" header="栏目名称" headerStyle="width: 8rem" />
                <Column field="hots" header="人气" />
                <Column header="缩图" field="ispic">
                    <template #body="{ data }">
                        <Tag :value="data.ispic ? '是' : '否'" :severity="data.ispic ? 'Success' : 'danger'"></Tag>
                    </template>
                </Column>
                <Column field="istop" header="置顶">
                    <template #body="{ data }">
                        <ToggleSwitch v-model="data.istop" @change="handleToggleChange('istop', data)"></ToggleSwitch>
                    </template>
                </Column>
                <Column field="isnice" header="推荐">
                    <template #body="{ data }">
                        <ToggleSwitch v-model="data.isnice" @change="handleToggleChange('isnice', data)"></ToggleSwitch>
                    </template>
                </Column>
                <Column header="状态" field="islock">
                    <template #body="{ data }"> <ToggleSwitch v-model="data.islock" @change="handleToggleChange('islock', data)"></ToggleSwitch></template>
                </Column>
                <Column header="操作" headerStyle="width: 10rem">
                    <template #body="{ data }">
                        <Button
                            icon="pi pi-pencil"
                            severity="info"
                            text
                            @click="
                                product = { ...data };
                                productDialog = true;
                            "
                        />
                        <Button icon="pi pi-trash" severity="danger" text @click="confirmDelete(data)" />
                    </template>
                </Column>
            </DataTable>
        </div>

        <!-- 编辑对话框 -->
        <Dialog v-model:visible="productDialog" header="内容编辑" :style="{ width: 'min(90vw, 600px)' }">
            <div class="grid gap-4 p-4">
                <div>
                    <label for="title" class="block font-bold mb-3">标题</label>
                    <InputText id="title" v-model.trim="product.title" required="true" autofocus fluid />
                </div>
                <div>
                    <label for="content" class="block font-bold mb-3">正文</label>
                    <Editor
                        v-model="product.content"
                        name="content"
                        editor-style="height: 320px"
                        :pt="{
                            content: { class: 'min-h-[200px]' },
                            toolbar: { class: 'border-round-top' }
                        }"
                        :disabled="isLoading"
                    />
                </div>
                <div>
                    <label for="pic" class="block font-bold mb-3">缩略图</label>
                    <div class="flex flex-wrap items-start gap-4">
                        <div class="field">
                            <InputText id="pic" v-model.trim="product.pic" required="true" fluid />
                        </div>
                        <ButtonGroup>
                            <Button label="上传" icon="pi pi-upload" @click="uploadImage" />
                            <Button label="选择" icon="pi pi-folder-open" />
                            <Button label="预览" icon="pi pi-eye" />
                        </ButtonGroup>
                    </div>
                </div>
            </div>

            <template #footer>
                <Button label="取消" severity="secondary" @click="closeDialog" />
                <Button label="保存" @click="handleSave" />
            </template>
        </Dialog>

        <!-- 批量删除确认 -->
        <Dialog v-model:visible="deleteProductsDialog" header="确认删除">
            <p>确定要删除选中的 {{ selectedProducts.length }} 项内容吗？</p>
            <template #footer>
                <Button label="取消" @click="deleteProductsDialog = false" />
                <Button label="删除" severity="danger" @click="handleBatchDelete" />
            </template>
        </Dialog>

        <ConfirmDialog />
    </div>
</template>

<style scoped>
.content-manager {
    max-width: 1200px;
    margin: 0 auto;
    padding: 1rem;
}

.p-toolbar {
    background: var(--surface-card);
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.p-datatable {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

@media (max-width: 768px) {
    .p-toolbar-group {
        flex-wrap: wrap;
        gap: 0.5rem;
    }

    .p-button {
        width: 100%;
    }
}
</style>
